<?php

namespace App\Http\Controllers\Admin;

use App\Jobs\SendEmail;
use App\Mail\NoticeMail;
use App\Mail\RefuseNoticeMail;
use App\Model\Goods;
use App\Model\GoodsPutaway;
use DB;
use App\User;
use Illuminate\Http\Request;


class PutAwayAuditController extends MasterController
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {

        $data = DB::table('audit_putaways_v')->orderBy('updated_at')->get();
        return view('admin.audit.putaway', compact('data'));
    }

    public function agree(Request $request)
    {
        $putAway = GoodsPutaway::where('id', '=', $request['id'])->first();
        Goods::create([
            "id"=>$putAway['id'],
            "name"=>$putAway['name'],
            "author"=>$putAway['author'],
            "intro"=>$putAway['intro'],
            "size"=>$putAway['size'],
            "price"=>$putAway['price'],
            "imgUrl"=>$putAway['imgUrl'],
            "genre_id"=>$putAway['genre_id'],
            "creator_id"=>$putAway['creator_id'],
            "stars"=>0,
            "status"=>1  //1代表可进行售买
        ]);
        GoodsPutaway::where('id','=',$request['id'])->delete();
        $user=User::where('id',$request['user_id'])->select('email','name')->first();
        $message="您的作品《".$putAway['name']."》已通过审核！";
        $mail = (new NoticeMail($user['name'],$message,"上架审核结果"))
            ->onConnection('redis')
            ->onQueue('emails');
        SendEmail::dispatch($user['email'],$mail);
        return parent::success('操作成功,审核结果已通过邮箱通知用户');
    }

    public function refuse(Request $request)
    {
        GoodsPutaway::where('id',$request['id'])->update(["status"=>false]);
        $user = User::where('id',$request['user_id'])->select('email','name')->first();
        $to=$user['email'];
        $username=$user['name'];
        $subject="上架审核结果";
        $message="您的作品《".$request['name']."》未通过审核！请您修改相关信息后重新提交申请！";
        $mail=(new RefuseNoticeMail($username,$message,$request['reason'],$subject))
        ->onConnection('redis')
        ->onQueue('emails');
        SendEmail::dispatch($to,$mail);
        return parent::success('操作成功,审核结果已通过邮箱通知用户');
    }
}
